package services.midas.impl;

import java.util.List;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

import play.Logger;
import play.Play;
import services.midas.MidasStubIntf;
import services.midas.assembler.Assembler;

public class MidasLocalStub implements MidasStubIntf {
	protected static final String HOST = Play.configuration.getProperty("service-host");
	protected static final String PORT = Play.configuration.getProperty("service-port");
	protected static final String BASE_URL = Play.configuration.getProperty("service-uri");
	
	protected <T> T getJSONResponse(String uri,Class<T> clazz){
		String url = String.format("%s:%s/%s/%s", HOST,PORT,BASE_URL,uri);
		Client client = Client.create();
		WebResource webResource = client.resource(url);
		ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
		T json = response.getEntity(clazz);
		return json;
	}
	
	protected JSONObject getJSONResponse(String uri,Object object){
		String url = String.format("%s:%s/%s/%s", HOST,PORT,BASE_URL,uri);
		Client client = Client.create();
		WebResource webResource = client.resource(url);
		ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class,object);
		JSONObject json = response.getEntity(JSONObject.class);
		return json;
	}
	
	protected int getResponse(String uri,Object object){
		String url = String.format("%s:%s/%s/%s", HOST,PORT,BASE_URL,uri);
		Client client = Client.create();
		WebResource webResource = client.resource(url);
		ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class,object);
		return response.getStatus();
	}

	@Override
	public Map<Long, String> getNetworkElements() throws JSONException {
		return Assembler.jsonArray2Map(this.getJSONResponse("networkElement", JSONArray.class));
	}

	@Override
	public JSONObject getReleaseAndBuild(String release, String build) throws JSONException {
		JSONArray result = this.getJSONResponse("releaseAndBuilds/list/" + release + "/" + build + "/1/1", JSONArray.class);
		return result.length() == 1 ? result.getJSONObject(0) : null;
	}
}
